import 'package:magma/heartbeat/helpers/magma_constant.dart';
import 'package:stacked/stacked.dart';
import '../heartbeat/blueprint/challenge_model.dart';

/// 任务管理器
class QuestManager extends BaseViewModel {
  // 任务列表（模拟数据库）
  final List<QuestModel> _quests = [];

  // 任务尝试记录列表
  final List<QuestAttemptModel> _attempts = [];

  // 当前正在进行的任务
  QuestAttemptModel? _activeAttempt;

  // 计时器状态
  DateTime? _chronometerStart;
  Duration _elapsedDuration = Duration.zero;

  /// 获取所有任务
  List<QuestModel> get quests => List.from(_quests);

  /// 获取当前正在进行的任务
  QuestAttemptModel? get activeAttempt => _activeAttempt;

  /// 获取计时器开始时间
  DateTime? get chronometerStart => _chronometerStart;

  /// 获取已用时间
  Duration get elapsedDuration => _elapsedDuration;

  /// 检查是否有正在进行的任务
  bool get hasActiveQuest =>
      _activeAttempt != null && !_activeAttempt!.isCompleted;

  /// 初始化默认任务数据
  void initializeDefaultQuests() {
    _quests.clear();
    _quests.addAll(_getDefaultQuests());
  }

  /// 获取默认任务数据
  List<QuestModel> _getDefaultQuests() {
    return [
      QuestModel(
        id: '1',
        title: 'Morning Sprint',
        distance: 5.0,
        minTime: 20,
        maxTime: 30,
        image: MagmaConstant.challenge2,
        description: 'Start your day with a refreshing 5km run',
      ),
      QuestModel(
        id: '2',
        title: 'Marathon Training',
        distance: 21.0,
        minTime: 90,
        maxTime: 120,
        image: MagmaConstant.challenge1,
        description: 'Half marathon distance training run',
      ),
      QuestModel(
        id: '3',
        title: 'City Explorer',
        distance: 10.0,
        minTime: 45,
        maxTime: 70,
        image: MagmaConstant.challenge3,
        description: 'Explore the city with a 10km urban run',
      ),
      QuestModel(
        id: '4',
        title: 'Hill Challenge',
        distance: 8.0,
        minTime: 40,
        maxTime: 60,
        image: MagmaConstant.challenge5,
        description: 'Conquer hills with this challenging 8km route',
      ),
      QuestModel(
        id: '5',
        title: 'Sunset Run',
        distance: 6.0,
        minTime: 25,
        maxTime: 40,
        image: MagmaConstant.challenge6,
        description: 'Enjoy the sunset with a peaceful 6km run',
      ),
      QuestModel(
        id: '6',
        title: 'Speed Demon',
        distance: 3.0,
        minTime: 12,
        maxTime: 18,
        image: MagmaConstant.challenge4,
        description: 'Test your speed with this intense 3km sprint',
      ),
    ];
  }

  /// 开始任务
  Future<bool> beginQuest(String questId, String userId) async {
    setBusy(true);
    try {
      // 检查是否已有正在进行的任务
      if (hasActiveQuest) {
        setError('You already have an active quest');
        return false;
      }

      // 查找任务（验证任务存在）
      _quests.firstWhere(
        (q) => q.id == questId,
        orElse: () => throw Exception('Quest not found'),
      );

      // 创建尝试记录
      final attempt = QuestAttemptModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        questId: questId,
        userId: userId,
        startTime: DateTime.now(),
      );

      _attempts.add(attempt);
      _activeAttempt = attempt;
      _chronometerStart = DateTime.now();
      _elapsedDuration = Duration.zero;

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 上传开始图片
  Future<bool> submitStartImage(String imagePath) async {
    setBusy(true);
    try {
      if (_activeAttempt == null) {
        setError('No active quest found');
        return false;
      }

      // 更新尝试记录
      final updatedAttempt = _activeAttempt!.copyWith(startImage: imagePath);

      final index = _attempts.indexWhere((a) => a.id == _activeAttempt!.id);
      if (index != -1) {
        _attempts[index] = updatedAttempt;
        _activeAttempt = updatedAttempt;
      }

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 完成任务
  Future<bool> finishQuest(String endImagePath) async {
    setBusy(true);
    try {
      if (_activeAttempt == null) {
        setError('No active quest found');
        return false;
      }

      if (_activeAttempt!.startImage == null) {
        setError('Start image is required');
        return false;
      }

      final endTime = DateTime.now();
      final duration = endTime.difference(_activeAttempt!.startTime);

      // 更新尝试记录
      final updatedAttempt = _activeAttempt!.copyWith(
        endTime: endTime,
        endImage: endImagePath,
        isCompleted: true,
        duration: duration,
      );

      final index = _attempts.indexWhere((a) => a.id == _activeAttempt!.id);
      if (index != -1) {
        _attempts[index] = updatedAttempt;
        _activeAttempt = null;
        _chronometerStart = null;
        _elapsedDuration = Duration.zero;
      }

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 取消任务
  void abandonQuest() {
    if (_activeAttempt != null) {
      _activeAttempt = null;
      _chronometerStart = null;
      _elapsedDuration = Duration.zero;
      notifyListeners();
    }
  }

  /// 更新计时器
  void refreshChronometer() {
    if (_chronometerStart != null && hasActiveQuest) {
      _elapsedDuration = DateTime.now().difference(_chronometerStart!);
      notifyListeners();
    }
  }

  /// 根据ID获取任务
  QuestModel? fetchQuestById(String questId) {
    try {
      return _quests.firstWhere((quest) => quest.id == questId);
    } catch (e) {
      return null;
    }
  }

  /// 获取用户的任务尝试记录
  List<QuestAttemptModel> retrieveUserAttempts(String userId) {
    return _attempts.where((a) => a.userId == userId).toList();
  }

  /// 获取已完成的任务
  List<QuestAttemptModel> fetchCompletedQuests(String userId) {
    return _attempts.where((a) => a.userId == userId && a.isCompleted).toList();
  }
}
